#include <stdlib.h>
#include <string>
#include <iostream>
#include <memory>
#include <rise/common/exmacros.h>
#include <rise/common/Log.h>
#include <rise/common/Exception.h>
#include <rise/common/DataEncoder.h>
#include <rise/common/StreamBuffer.h>
#include <rise/common/PerformanceCounter.h>
#include <staff/common/Value.h>
#include <staff/common/QName.h>
#include <staff/common/Attribute.h>
#include <staff/common/DataObject.h>
#include <staff-mq/client/Publisher.h>


int main(int nArgs, char* szArgs[])
{
  std::string sServerHost = "127.0.0.1";
  unsigned short ushServerPort = 8768;

  for (int nArg = 1; nArg < nArgs; ++nArg)
  {
    if(szArgs[nArg])
    {
      const std::string& sArg = std::string(szArgs[nArg]);
      if (sArg.substr(0, 2) == "-s")
      {
        sServerHost = sArg.substr(2);
      }
      else
      if (sArg.substr(0, 2) == "-p")
      {
        ushServerPort = static_cast<unsigned short>(atoi(sArg.substr(2).c_str()));
      }
      else
      if (sArg.substr(0, 2) == "-h")
      {
        std::cerr << "Publisher multithreading test.\n\n"
            << szArgs[0] << "[ -h][ -s<Server host>][ -p<port>]\n\n";
        return 0;
      }
      else
      {
        std::cerr << "unknown arg: " << sArg << "\n";
        return 1;
      }
    }
  }


  try
  {
    smq::Publisher tPublisher;
    tPublisher.Init("publisher_test2clients", sServerHost, ushServerPort);

    tPublisher.CreateQueue("queue1");
    tPublisher.CreateQueue("queue2");

    // first message type
    {
      staff::CDataObject tdoMsg("msg");


      // publishing into queue
      std::cout << "Publishing message into \"queue1\"" << std::endl;
      tdoMsg.SetText("message to first queue");
      tPublisher.Publish("queue1", tdoMsg);

      std::cout << "Publishing message into \"queue2\"" << std::endl;
      tdoMsg.SetText("message to second queue");
      tPublisher.Publish("queue2", tdoMsg);

      std::cout << "Publishing message into \"queue*\"" << std::endl;
      tdoMsg.SetText("message to queue*");
      tPublisher.Publish("queue*", tdoMsg);
    }

    tPublisher.RemoveQueue("queue1");
    tPublisher.RemoveQueue("queue2");
  }
  RISE_CATCH_ALL

  return 0;
}
